package org.domain.jeelinklibraryknuppmoosweb.session;

import java.util.List;



import javax.ejb.Stateful;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.Destroy;
import org.jboss.seam.annotations.End;
import org.jboss.seam.annotations.Factory;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Logger;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Out;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.faces.FacesMessages;
import org.jboss.seam.international.StatusMessages;
import org.jboss.seam.log.Log;

import ch.ffhs.links_library.entities.*;
import javax.ejb.Remove;

@Stateful
@Scope(ScopeType.CONVERSATION)
@Name("LinksHandler")

public class LinksHandler
{
    @Logger private Log log;

    @In StatusMessages statusMessages;
    
	/*
	 * Message context for faces Messages
	 */
	@In
	FacesMessages facesMessages;
	
    /* 
     * Persistence context - database
     */
	@PersistenceContext
	private EntityManager em;
	
	public LinksHandler () {
		log.info("linkHandler created");
		getAllLinks();
		log.info(linklist.toString());
	}
	/**
	 * Available links.
	 */
	@Out(required=false, scope=ScopeType.CONVERSATION)
	private List<Link> linklist;
	

    public List<Link> linksAdd()
    {
        // implement your business logic here
        log.info("links.linksAdd() action called");
        statusMessages.add("linksAdd");
        
        return linklist;
        //return "links";
    }

	//-------------------Factory Methoden-------------------
	/**
	 * Gibt alle Links, welche nicht als geloescht markiert sind, als Liste zurueck.
	 * @return List Liste mit den Linksn
	 */
	@Factory("linklist")
	public List<Link> getAllLinks(){
		log.info("@Factory(linksliste) --> public List<Links> getAlleLinks()");
		
		//Alle Links die nicht geloescht wurden.
		if(linklist == null){
			log.info("Liste ist NULL");
			
			return em.createQuery("SELECT l FROM link AS l").getResultList();
		}
		return linklist;
	}
	
	public void createLink(Link l) {
		em.persist(l);
		log.info("link persisted");
	}


	@Remove
	@Destroy
	public void remove() {
	}

}
